<template>
	<theme-box title="自定义菜单" theme="primary" class="custom-menu">
			<style>
				.box-container {
					width:200px;
					margin: 10px auto;
				}
			</style>
	 <div class="alert alert-default clearfix">
	 		<div class="col-sm-6">
				<form-group title="菜单组" left="4">
					<select class="form-control" @change="resetMenu" v-el:group>
						<option :value="item.value" v-for="item in groups">{{item.key}}</option>
					</select>
				</form-group>
	 		</div>
		</div>
		<div class="row">
			<div class="col-md-4">
				<div class="panel panel-default main-panel-left">
					<div class="box-header with-border">
						<h4 class="box-title">编辑菜单
						</h4>
						<div class="box-tools">
							<button type="button" style="color:#3c8dbc" class="btn btn-box-tool" @click="publish">发布菜单
							<i class="fa fa-refresh"></i>
							</button>
						</div>
					</div>
					<div class="panel-footer">
						<ul class = "list-group-horizontal">
							 <li class = "list-group-item dropdown "   v-for="(index,item) in menu">
							 	<a class="dropdown-toggle" data-toggle="dropdown" @click="edit(item,index)">
							 		<span v-if="item.menuId">{{item.menuName}}</span>
							 		<span v-else><i class="fa fa-plus"></i></span>
							 	</a>
							 	<!-- 上级已建立,显示下级 -->
							 	<ul class="dropdown-menu list-group" v-if="item.menuId">
							 		<li class = "list-group-item" v-for="obj in item.children" @click.stop="edit(obj,index)">
							 			{{obj.menuName}}
							 		</li>
							 		<li class="list-group-item" @click.stop="appendChild(item,index)">
							 			<span><i class="fa fa-plus"></i></span>
							 		</li>
							 	</ul>
							 </li>
						</ul>
					</div>
					<div class='text-center'>

					</div>
				</div>
			</div>

			<div class="col-md-8">
				<div class="panel panel-default  main-panel-right">

					<div class="box-header with-border">
						<h4 class="box-title" v-if="isEdit()">
							<span v-if="isParent()">编辑菜单-{{editRawData.menuName}}</span>
							<span v-else>编辑{{hintName}}子菜单-{{editRawData.menuName}}  </span>
						</h4>
						<h4 class="box-title" v-else>
							<span v-if="isParent()">新建菜单编辑</span>
							<span v-else>菜单{{hintName}}-新建子菜单</span>
						</h4>
						<div class="box-tools">
							<button type="button" class="btn btn-box-tool" @click="removeMenu()">删除菜单  <i class="fa fa-times"></i></button>
						</div>
					</div>
					<div class="panel-container">
						<div class="panel-body">
						  <form-input v-if="isParent()" title="菜单名称" left="3" @keyup="size(8,$event)"
						  :value.sync="editModel.menuName" placeholder="字数不超过4个汉字或8个字母">
						  </form-input>
							<form-input v-else title="子菜单名称" left="3" @keyup="size(16,$event)"
							:value.sync="editModel.menuName" placeholder="字数不超过8个汉字或16个字母">
							</form-input>

							<form-group title="菜单内容" left="3" v-show="!hasChild()">
								<label class="radio-inline"> <div class="radio"><input type="radio" name="options" value="1" v-model="editModel.type" checked></div> 发送信息 </label>
								<label class="radio-inline"> <div class="radio"><input type="radio" name="options" value="2" v-model="editModel.type"></div> 跳转网址 </label>
							</form-group>
						</div>
						<div class="panel-footer">
							<div v-show="!hasChild()">
								<app-box v-if="isMessage()" v-ref:box></app-box>
								<div v-else>
										<form-input title="页面网址" left="3" placeholder="请输入跳转页面网址" :value.sync="editModel.url"></form-input>
										<div class="divide-40"></div>
								</div>
							</div>
							<div class="clearfix">
							<!--
							<v-button theme="warning" style="margin-left:15px" class="pull-right" @click="publish">发布</v-button> -->
							<v-button theme="primary" @click="save" class="pull-left">保存</v-button>
							<div class="pull-right" style="line-height:32px;color:#777">保存所有操作后，选择发布菜单，一定时间内生效</div>
							</div>
						</div>

					</div>
				</div>
			</div>
		</div>
	</theme-box>
</template>
<style lang="less" src="assets/style/menu.less"></style>
<script>

	import Box from 'pages/partial/box.vue';

	export default {
		data: () => ({
			groups:[],
			//编辑中主菜单名
			hintName:"",
			editIndex:""
		}),
		components: {
			'app-box': Box,
//		  'app-list':List
		},
		props: {
			menu: {
				type: Array,
				twoWay: true,
				default: function() {
					return []
				}
			},
			editModel: {
				type: Object
			},
			editRawData: {
				type: Object
			}
		},
		beforeCompile() {
			let editModel = {};
			this.$set("editModel",editModel);

			let model = [this.model(),this.model(),this.model()];
			this.$set("menu",model);
		},
//		events: {
//			'mid-watcher':function(data) {
//				let _data = {}
//				this.getGroup(_data);
//				this.resetMenu();
//			},
//			'mid-done':'dataInit'
//		},
		methods: {
			isMessage() {
				return (this.editModel.type == 1)?true:false;
			},
			size(maxlength,e) {
//bug
//let str = e.target.value;
				let str = this.editModel.menuName;
			  let length = 0
				let replace = false;
				let replaceStr = "";
				for (let i=0;i<str.length;i++){
					let char = str.charAt(i);
			　　 let reg = new RegExp("[\\u4E00-\\u9FFF]+","g");
					if (reg.test(char)){
						if(length+2>maxlength) {
							replace = true;
							break;
						} else {
							length+=2;
							replaceStr+=char;
						}
					} else {
						if(length+1>maxlength) {
							replace = true;
							break;
						} else {
							length+=1;
							replaceStr+=char;
						}
					}
				}
				if(replace) {
					e.target.value = replaceStr;
				}
			},
			isEdit() {
				if(!this.editRawData) {
					return false;
				}
				if(this.editRawData.hasOwnProperty('menuId')){
					let id = this.editRawData.menuId;
					id = $.trim(id);
					if(id) {
						return true
					} else {
						return false
					}
				} else {
					return false
				}
			},
			isParent() {
				if(this.editRawData) {
					return (this.editRawData.hasOwnProperty('children'))?true:false;
				} else {
					return false;
				}

			},
			hasChild() {
				if(this.isParent()){
					return (this.editRawData.children.length>0)?true:false;
				} else {
					return false
				}
			},
			dataInit() {
				let _data = {};
				let self = this;
				//初化菜单
			  self.getGroup(_data,function(){
					_data.groupId = self.$els.group.value;
	  			_data.mchtIdFlag = localStorage.getItem('get_id')
					self.getMenu(_data);
				});
			},
			//获得组别
			getGroup(data,done) {
				this.$search({
					url:"/api/v1" + projectName_Url + "/list/groupId.html",
					data
				}).then((response)=>{
				},list=>{
					this.$set("groups",list.info);
					this.$nextTick(()=>{
						if(done){
							done();
						}
					})
				})
			},
			//显示菜单
			loadData(list) {
					let self = this;
					let data = list.filter((arr) => {
						return (arr.parentId == "-");
					}).map((arr)=>{
						let id = arr.id.menuId;
						arr.menuId = id;
						delete arr.id;
						//不显示编辑项
//						arr.type = 1;
//						delete arr.url;

						let children = list.filter(sum=>{
							return (sum.parentId == id);
						}).map((arr)=>{
							arr.menuId = arr.id.menuId;
							delete arr.id;
						  //不显示编辑项
//							arr.type = 1;
//							delete arr.url;
							
							return arr
						});
						arr.children = children;
						return arr;
					});
					let model = [this.model(),this.model(),this.model()];
					//parentId
					let menu = Object.assign(model,data)

					this.$set("menu",menu);
					this.edit(menu[0]);
			},
			//获取菜单
			getMenu(data) {
				let self = this;
				this.$search({
					url:"/api/v1" + projectName_Url + "/wechat/menu/query.html",
					data
				}).then((response)=>{
					let list = response.content.menuList;
					self.loadData(list);
				},error=>{})
			},
			resetMenu() {
				let data = {};
				data.groupId = this.$els.group.value;
	  		data.mchtIdFlag = localStorage.getItem('get_id')
				this.getMenu(data);
			},
			setOption(data) {
			  this.$set("isMessage", data);
			},
			removeMenu() {
				let model = this.editRawData;
				let self = this;
				if(!model.menuId) {
					if(this.isParent()){
						this.$set("editModel",model);
					} else {
						this.menu[this.editIndex].children.$remove(model);
						this.edit(this.menu[this.editIndex]);
					}
					return false;
				}

					let message = {
						title: "操作提示",
						content: "是否删除菜单"+model.menuName+"?"
					}
					let data = {};
					data.menuId = model.menuId;

				  data.mchtIdFlag = localStorage.getItem('get_id')
					data.groupId = this.$els.group.value;
					Midway.confirm(message).then(()=>{
						this.$post({
							url:"/api/v1" + projectName_Url + "/wechat/menu/del.html",
							data
						}).then((response)=>{

							let alert = {
								title:"操作提示",
								content:"删除成功"
							}
							Midway.alert(alert);

							//this.resetMenu();
							model.menuId = "";
							if(this.isParent()){
								this.$set("editModel", model);
							} else {
								this.menu[this.editIndex].children.$remove(model);
								this.edit(this.menu[this.editIndex]);
							}

						},error=>{})
					})
			},
			appendChild(item,index) {
				let self = this;
				if(item.children.length<5) {
					/*增一存一
					let flag = true;
					item.children.every(obj=>{
						if(!obj.menuId) {
							flag = false;
							return false;
						} else {
							return true;
						}
					})
					if(!flag) {
						let message = {
							title:"操作提示",
							content:"菜单「"+self.hintName+"」下有尚未保存的子菜单,请保存后继续增加"
						}
						Midway.alert(message);
						return false;
					}
					*/
					let model = this.chlidModel();
					model.parentId = item.menuId;
					item.children.push(model);
					this.edit(model,index);
				}
			},
			edit(item,index) {				
				
				let menuId = item.menuId;
				//当前对象已存在
				let self = this;
				if(menuId) {
					if(item.type == 1) {
						//查询当前详细内容
						let data = {
							menuId:item.menuId,
							menuKey:item.menuKey,
							groupId:item.groupId,
							mchtId: localStorage.getItem('get_id')
						}										
						this.$post({
							url:"/api/v1" + projectName_Url + "/wechat/menu/menuInf.html",
							data
						}).then((response)=>{
							  let obj = response.content.menuInf[0];
								if(obj.type == "news") {
									self.$refs.box.$set("msgType",obj.type);
								} else {
									self.$refs.box.$set("msgType",obj.msgType);									
								}
								if(obj.msgType == "image") {		
									 let _id = {
										 media: obj.mediaId,
									 }					 
//									 obj.url = obj.picUrl;
									 obj.id = _id;					 				
									 self.$refs.box.setPhoto(obj);
								} else if(obj.type == "news") {
									 let _id = {
										 media: obj.mediaId,
										 artId: obj.articleIds
									 }					 
									 obj.id = _id;					 
									 self.$refs.box.setResource(obj);
								} else {
									 self.$refs.box.$set("content",obj.content);
								}

						},error => {})
					}					
				}				
								
				//判断是否为当前编辑对象，若是不进行操作				
				let isOne = Object.is(item,this.editRawData);
				this.$set("editIndex",index);
				if(isOne) {
					return false;
				}
				
				let model = _.cloneDeep(item);
				this.$set("editRawData",item);
				this.$set("editModel",model);
				this.$refs.box.clear();

				let obj = this.menu[index];
				if(obj && obj.hasOwnProperty("menuName")) {
						this.$set("hintName",this.menu[index].menuName)
				}
				//this.$set("mainEditIndex",index)
			},
			model() {
				let model = {
					menuName:"菜单名称",
					children: [],
					parentId: "-"
				}
				return Object.assign(this.chlidModel(),model)
			},
			chlidModel() {
				return {
					menuName: "子菜单名称",
					menuId: "",
					parentId: "",
					type: 1,
					groupId: "",
					url: "",
					menuKey: "key",
					orderNo: parseInt( (Math.random()*9+1)*1000 )
				}
			},
			save() {
				let rawData = _.cloneDeep(this.editRawData);
				let model = Object.assign(rawData,this.editModel);
				let data = model;
				data.mchtIdFlag = localStorage.getItem('get_id')
				data.groupId = this.$els.group.value;
				//发送信息
				let stop = false;
				if(data.type == 1) {
					if(this.hasChild()) {
						stop = false;
					} else if(this.$refs.box.valid()){
						data = Object.assign(data,this.$refs.box.get());
					} else {
						stop = true;
					}
				}
				if(stop) {
					return false;
				}
				delete data.children;

				if(model.menuId) {
					//更新数据
					this.$post({
						url:"/api/v1" + projectName_Url + "/wechat/menu/upd.html",
						data
					}).then((response)=>{
						//编辑成功
						let message = {
							title: "操作提示",
							content: "保存成功"
						}
						Midway.alert(message);

						Object.assign(this.editRawData,this.editModel)
//					this.resetMenu();
//					let list = response.content.menuList;
//					this.loadData(list);
					});
					return false;
				} else {
					//新增数据
					this.$post({
						url:"/api/v1" + projectName_Url + "/wechat/menu/add.html",
						data
					}).then((response)=>{
						let message = {
							title: "操作提示",
							content: "保存成功"
						}
						Midway.alert(message);

						this.resetMenu();
//						let list = response.content.menuList;
//						this.loadData(list);
					},error=>{})

				}

			},

			publish() {
				let self = this;
				let message = {
					title:"温馨提示--请勿重复操作",
					content:"发布成功后会覆盖原版本，且将在24小时内对所有用户生效，确认发布？"
				}
				Midway.confirm(message).then(()=>{
					let data = {};

					data.mchtIdFlag = localStorage.getItem('get_id');
					data.groupId = self.$els.group.value;
					self.$post({
						url:"/api/v1" + projectName_Url + "/wechat/menu/menuSyn.html",
						data
					}).then(response =>{
						let message = {
							title:"操作提示",
							content:"同步菜单成功"
						}
						Midway.alert(message);
					},error =>{})
				});
			}

	  },
		ready() {

				this.dataInit();
		}

	}
</script>
